#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

#define NUM 128
#define SIZE 32
char command_line[NUM];
char *command_parse[SIZE];


int main() {
    while (1) {
        memset(command_line, '\0', sizeof(command_line));
        printf("[xupeng@myhost 我的shell]$ ");
        fflush(stdout);
        if (fgets(command_line, NUM, stdin)) {
            command_line[strlen(command_line) - 1] = '\0';
            int index = 0;
            command_parse[index] = strtok(command_line, " ");
            //printf("index%d -> %s\n",index,  command_parse[index]);
            while (1) {
                index++;
                command_parse[index] = strtok(NULL, " ");
                if (command_parse[index] == NULL) {
                    break;
                }
            }
            if (strcmp(command_parse[0], "cd") == 0 && chdir(command_parse[1]) == 0)
            {
                continue;
            }
            //printf("----> %s", command_line);
            if (fork() == 0) {
                execvp(command_parse[0], command_parse);
                exit(1);
            }
            int status = 0;
            pid_t ret = waitpid(-1, &status, 0);
            if (ret > 0 && WIFEXITED(status)) {
                printf("Exit code : %d\n", WEXITSTATUS(status));
            }
        }
    }
    return 0;
}
